import { app, BrowserWindow, screen } from 'electron'
import { getData, setData } from '@/puppeteer/common'
import { daMai } from '@/puppeteer/daMai'

const { ipcMain } = require('electron')
const os = require('os')
const fs = require('fs')
const path = require('path')

process.env.DEFAULT_DOWNLOAD_PATH = path.join(os.homedir(), 'Downloads')
process.env.COOKIEPATH = path.join(process.env.DEFAULT_DOWNLOAD_PATH, 'cookie')
process.env.ELECTRONDATAPATH = path.join(process.env.DEFAULT_DOWNLOAD_PATH, 'electrondata')

// 等待Electron应用就绪后创建BrowserWindow窗口
app.whenReady().then(async () => {
  const win = await new BrowserWindow({
    show: true,
    width: 980,
    height: 720,
    minWidth: 868,
    minHeight: 686,
    frame: true,
    // 配置窗口的WebPreferences选项，用于控制渲染进程的行为
    webPreferences: {
      nodeIntegration: true, // 启用Node.js集成
      contextIsolation: false, // 禁用上下文隔离
      webSecurity: false // 禁用web安全策略
    }
  })
  win.webContents.openDevTools()

  // 根据命令行参数加载URL或本地文件
  if (process.argv[2]) {
    win.loadURL(process.argv[2])
  } else {
    win.loadFile('index.html')
  }
  /**
   * @description 监听渲染进程发送的消息
   * @param event 事件对象 params 参数
   */
  ipcMain.on('saveTableData', (_, params) => {
    console.log('saveData', params)
    setData(params)
  })

  /**
   * @description 监听渲染进程发送的消息
   * @param event 事件对象
   * @returns 返回数据
   */
  ipcMain.on('getTableData', (event) => {
    const data = getData()
    const responseTableData = data ? JSON.parse(data) : []
    event.reply('responseTableData', responseTableData)
  })

  ipcMain.on('createNewPage', (_) => {
    const cookieName = 'test'
    daMai.createPage()
  })

  ipcMain.on('login', (_) => {
    const cookieName = 'test'
    daMai.login(cookieName)
  })
})
